<template>
  <div class="assignment-table">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="裁判姓名">
          <el-input v-model="searchForm.refereeName" placeholder="请输入裁判姓名" clearable style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="执裁角色">
          <el-select v-model="searchForm.role" placeholder="请选择执裁角色" clearable style="width: 150px">
            <el-option label="主裁判" value="主裁判"></el-option>
            <el-option label="副裁判" value="副裁判"></el-option>
            <el-option label="记录员" value="记录员"></el-option>
            <el-option label="计时员" value="计时员"></el-option>
            <el-option label="检录员" value="检录员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 220px">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="filteredData"
      v-loading="loading"
      stripe
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      empty-text="暂无数据">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="分配ID" width="80" align="center"></el-table-column>
      <el-table-column prop="refereeName" label="裁判姓名" width="120" align="center">
        <template #default="scope">
          <div class="referee-info">
            <span class="referee-name">{{ scope.row.refereeName }}</span>
            <el-tag size="mini" :type="getLevelTagType(scope.row.levelName)">
              {{ scope.row.levelName }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="refereePhone" label="联系电话" width="130" align="center"></el-table-column>
      <el-table-column prop="refereeDepartment" label="所属部门" width="150" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="projectName" label="项目名称" width="150" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="projectType" label="项目类型" width="100" align="center">
        <template #default="scope">
          <el-tag size="small" :type="getProjectTypeTag(scope.row.projectType)">
            {{ scope.row.projectType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="执裁角色" width="100" align="center">
        <template #default="scope">
          <el-tag size="small" :type="getRoleTagType(scope.row.role)">
            {{ scope.row.role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="eventDate" label="比赛时间" width="180" align="center">
        <template #default="scope">
          <div class="event-time">
            <div>{{ formatDate(scope.row.eventDate) }}</div>
            <div class="time-range">{{ scope.row.startTime }} - {{ scope.row.endTime }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="比赛地点" width="120" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="assignedAt" label="分配时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.assignedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="assignedBy" label="分配人" width="100" align="center"></el-table-column>
      <el-table-column v-if="status === 'REJECTED'" prop="rejectReason" label="拒绝原因" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="scope">
          <el-button-group size="mini">
            <el-button type="primary" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
            <el-button
              v-if="status === 'PENDING'"
              type="success"
              icon="el-icon-check"
              @click="handleAccept(scope.row)">
              接受
            </el-button>
            <el-button
              v-if="status === 'PENDING'"
              type="warning"
              icon="el-icon-close"
              @click="handleReject(scope.row)">
              拒绝
            </el-button>
            <el-button
              v-if="status === 'PENDING' || status === 'ACCEPTED'"
              type="danger"
              icon="el-icon-close"
              @click="handleCancel(scope.row)">
              取消
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 批量操作 -->
    <div class="batch-operations" v-if="selectedAssignments.length > 0">
      <span>已选择 {{ selectedAssignments.length }} 项</span>
      <el-button v-if="status === 'PENDING'" type="success" size="small" @click="handleBatchAccept">批量接受</el-button>
      <el-button v-if="status === 'PENDING'" type="warning" size="small" @click="handleBatchReject">批量拒绝</el-button>
      <el-button v-if="status === 'PENDING' || status === 'ACCEPTED'" type="danger" size="small" @click="handleBatchCancel">批量取消</el-button>
      <el-button type="info" size="small" @click="handleBatchExport">批量导出</el-button>
    </div>

    <!-- 分配详情对话框 -->
    <el-dialog
      title="分配详情"
      v-model="detailDialogVisible"
      width="800px">
      <div v-if="currentAssignment" class="assignment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分配ID">{{ currentAssignment.id }}</el-descriptions-item>
          <el-descriptions-item label="分配状态">
            <el-tag :type="getStatusTagType(currentAssignment.status)">
              {{ getStatusText(currentAssignment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="裁判姓名">{{ currentAssignment.refereeName }}</el-descriptions-item>
          <el-descriptions-item label="资质等级">
            <el-tag :type="getLevelTagType(currentAssignment.levelName)" size="small">
              {{ currentAssignment.levelName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentAssignment.refereePhone }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ currentAssignment.refereeDepartment }}</el-descriptions-item>
          <el-descriptions-item label="专长项目">{{ currentAssignment.specialty }}</el-descriptions-item>
          <el-descriptions-item label="执裁角色">{{ currentAssignment.role }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ currentAssignment.projectName }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag size="small" :type="getProjectTypeTag(currentAssignment.projectType)">
              {{ currentAssignment.projectType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="比赛时间">{{ formatDate(currentAssignment.eventDate) }} {{ currentAssignment.startTime }}-{{ currentAssignment.endTime }}</el-descriptions-item>
          <el-descriptions-item label="比赛地点">{{ currentAssignment.location }}</el-descriptions-item>
          <el-descriptions-item label="分配人">{{ currentAssignment.assignedBy }}</el-descriptions-item>
          <el-descriptions-item label="分配时间">{{ formatDateTime(currentAssignment.assignedAt) }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAssignment.respondedAt" label="响应时间">{{ formatDateTime(currentAssignment.respondedAt) }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAssignment.rejectReason" label="拒绝原因" :span="2">{{ currentAssignment.rejectReason }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAssignment.remarks" label="备注信息" :span="2">{{ currentAssignment.remarks }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 拒绝原因对话框 -->
    <el-dialog
      title="拒绝分配"
      v-model="rejectDialogVisible"
      width="500px">
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="100px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmReject" :loading="rejectLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AssignmentTable',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: ''
    }
  },
  emits: ['accept', 'reject', 'cancel', 'refresh'],
  data() {
    return {
      // 搜索表单
      searchForm: {
        refereeName: '',
        role: '',
        dateRange: []
      },

      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 选中的分配
      selectedAssignments: [],

      // 对话框状态
      detailDialogVisible: false,
      rejectDialogVisible: false,
      currentAssignment: null,
      rejectLoading: false,

      // 拒绝表单
      rejectForm: {
        assignmentId: null,
        reason: ''
      },
      rejectRules: {
        reason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' },
          { min: 5, max: 200, message: '拒绝原因长度在 5 到 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // 过滤后的数据
    filteredData() {
      let result = [...this.data]

      // 按裁判姓名过滤
      if (this.searchForm.refereeName) {
        result = result.filter(item =>
          item.refereeName && item.refereeName.includes(this.searchForm.refereeName)
        )
      }

      // 按执裁角色过滤
      if (this.searchForm.role) {
        result = result.filter(item =>
          item.role && item.role === this.searchForm.role
        )
      }

      // 按日期范围过滤
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        const [startDate, endDate] = this.searchForm.dateRange
        result = result.filter(item => {
          if (!item.eventDate) return false
          const eventDate = item.eventDate.split(' ')[0]
          return eventDate >= startDate && eventDate <= endDate
        })
      }

      // 分页
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return result.slice(start, end)
    },

    // 过滤后的总数
    filteredTotal() {
      let result = [...this.data]

      // 按裁判姓名过滤
      if (this.searchForm.refereeName) {
        result = result.filter(item =>
          item.refereeName && item.refereeName.includes(this.searchForm.refereeName)
        )
      }

      // 按执裁角色过滤
      if (this.searchForm.role) {
        result = result.filter(item =>
          item.role && item.role === this.searchForm.role
        )
      }

      // 按日期范围过滤
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        const [startDate, endDate] = this.searchForm.dateRange
        result = result.filter(item => {
          if (!item.eventDate) return false
          const eventDate = item.eventDate.split(' ')[0]
          return eventDate >= startDate && eventDate <= endDate
        })
      }

      return result.length
    }
  },

  watch: {
    data() {
      this.pagination.total = this.filteredTotal
      if (this.pagination.currentPage > Math.ceil(this.filteredTotal / this.pagination.pageSize)) {
        this.pagination.currentPage = 1
      }
    },
    filteredTotal(newTotal) {
      this.pagination.total = newTotal
      if (this.pagination.currentPage > Math.ceil(newTotal / this.pagination.pageSize)) {
        this.pagination.currentPage = 1
      }
    },
    'searchForm.refereeName'() {
      this.pagination.currentPage = 1
    },
    'searchForm.role'() {
      this.pagination.currentPage = 1
    },
    'searchForm.dateRange'() {
      this.pagination.currentPage = 1
    }
  },

  methods: {
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        refereeName: '',
        role: '',
        dateRange: []
      }
      this.pagination.currentPage = 1
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },

    // 表格选择改变
    handleSelectionChange(selection) {
      this.selectedAssignments = selection
    },

    // 查看详情
    handleView(row) {
      this.currentAssignment = row
      this.detailDialogVisible = true
    },

    // 接受分配
    handleAccept(row) {
      this.$confirm('确定要接受该分配吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.$emit('accept', row.id)
      })
    },

    // 拒绝分配
    handleReject(row) {
      this.rejectForm.assignmentId = row.id
      this.rejectForm.reason = ''
      this.rejectDialogVisible = true
    },

    // 确认拒绝
    handleConfirmReject() {
      this.$refs.rejectFormRef.validate((valid) => {
        if (valid) {
          this.rejectLoading = true
          this.$emit('reject', this.rejectForm.assignmentId, this.rejectForm.reason)
          this.rejectDialogVisible = false
          this.rejectLoading = false
        }
      })
    },

    // 取消分配
    handleCancel(row) {
      this.$confirm('确定要取消该分配吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('cancel', row.id)
      })
    },

    // 批量接受
    handleBatchAccept() {
      if (this.selectedAssignments.length === 0) {
        this.$message.warning('请选择要接受的分配')
        return
      }

      this.$confirm(`确定要接受选中的 ${this.selectedAssignments.length} 个分配吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.selectedAssignments.forEach(assignment => {
          this.$emit('accept', assignment.id)
        })
        this.selectedAssignments = []
      })
    },

    // 批量拒绝
    handleBatchReject() {
      if (this.selectedAssignments.length === 0) {
        this.$message.warning('请选择要拒绝的分配')
        return
      }

      this.$prompt('请输入拒绝原因', '批量拒绝分配', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '请输入拒绝原因'
      }).then(({ value }) => {
        this.selectedAssignments.forEach(assignment => {
          this.$emit('reject', assignment.id, value)
        })
        this.selectedAssignments = []
      })
    },

    // 批量取消
    handleBatchCancel() {
      if (this.selectedAssignments.length === 0) {
        this.$message.warning('请选择要取消的分配')
        return
      }

      this.$confirm(`确定要取消选中的 ${this.selectedAssignments.length} 个分配吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedAssignments.forEach(assignment => {
          this.$emit('cancel', assignment.id)
        })
        this.selectedAssignments = []
      })
    },

    // 批量导出
    handleBatchExport() {
      if (this.selectedAssignments.length === 0) {
        this.$message.warning('请选择要导出的分配')
        return
      }

      // 这里实现导出逻辑
      this.$message.success('导出功能开发中')
    },

    // 获取项目类型标签类型
    getProjectTypeTag(type) {
      const typeMap = {
        '田径': 'success',
        '球类': 'primary',
        '游泳': 'warning',
        '体操': 'danger',
        '武术': 'info'
      }
      return typeMap[type] || 'primary'
    },

    // 获取资质等级标签类型
    getLevelTagType(levelName) {
      const typeMap = {
        '国家级': 'danger',
        '省级': 'warning',
        '市级': 'primary',
        '校级': 'success',
        '实习': 'info'
      }
      return typeMap[levelName] || 'primary'
    },

    // 获取角色标签类型
    getRoleTagType(role) {
      const typeMap = {
        '主裁判': 'danger',
        '副裁判': 'warning',
        '记录员': 'primary',
        '计时员': 'success',
        '检录员': 'info'
      }
      return typeMap[role] || 'primary'
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        'PENDING': 'warning',
        'ACCEPTED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return typeMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待确认',
        'ACCEPTED': '已接受',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleDateString('zh-CN')
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.assignment-table {
  width: 100%;
}

/* 搜索栏 */
.search-bar {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 表格样式 */
.referee-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.referee-name {
  font-weight: 500;
}

.event-time {
  text-align: center;
}

.time-range {
  font-size: 12px;
  color: #909399;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 批量操作 */
.batch-operations {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-operations span {
  font-weight: 500;
  color: #606266;
}

/* 分配详情 */
.assignment-detail {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar .el-form-item {
    display: block;
    margin-bottom: 16px;
  }

  .search-bar .el-form-item .el-input,
  .search-bar .el-form-item .el-select,
  .search-bar .el-form-item .el-date-picker {
    width: 100% !important;
  }

  .batch-operations {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .batch-operations .el-button {
    width: 100%;
  }
}
</style>